package com.gitee.deament.server.core.cli.db.sortset;

import com.gitee.deament.server.config.SystemConfig;
import com.gitee.deament.server.core.annotation.CliHander;
import com.gitee.deament.server.core.cli.AbstractCli;
import com.gitee.deament.server.core.data.ConnectData;
import com.gitee.deament.server.core.data.ZSortSet;
import com.gitee.deament.server.core.data.ZSortSetMember;
import com.gitee.deament.server.core.data.datatype.Value;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.math.BigDecimal;
import java.util.List;

/**
 * ZCARD key
 * 可用版本： >= 1.2.0
 * 时间复杂度: O(1)
 * 返回有序集 key 的基数。
 *
 * 返回值
 * 当 key 存在且是有序集类型时，返回有序集的基数。 当 key 不存在时，返回 0 。
 * @author deament
 */
@CliHander(command = "ZCARD")
public class ZCARDcli extends AbstractCli {
    @Override
    public void executeCli(ChannelHandlerContext channelHandlerContext, String command) {
        List<String> cliValues = getValues(command);
        if (cliValues.size() !=2) {
            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("ERR wrong number of arguments for 'ZCARD' command"));
            return;
        }
        String key = cliValues.get(1);

        int db = ConnectData.SELECT_DB_STORAGE.getUseDB(channelHandlerContext.channel().id().asLongText());
        try {

            Value<ZSortSet> zSortSetData = SystemConfig.dbData.getZSortSetData(db, key);
            if(zSortSetData==null ||zSortSetData.getValue()==null ||zSortSetData.getValue().getData()==null){
                channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("0"));
                return;
            }

            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(zSortSetData.getValue().getData().size()+""));
            return;

        }catch (Exception e){
            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(e.getMessage()));
            return;
        }
    }
}
